package com.ymh.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.ymh.common.domain.ResultData;
import com.ymh.domain.ProductDTO;
import com.ymh.feign.ProductFeign;
import com.ymh.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 13590
 * @date: 2020/10/27 20:11
 * @description:
 */
@RestController
@Slf4j
public class ProductController implements ProductFeign {

  @Autowired
  private ProductService productService;

  @Override
  @PostMapping("/insert")
  public ResultData<String> insert(@RequestBody ProductDTO productDTO) {
    log.info("insert product:{}", productDTO);
    productService.insertProduct(productDTO);
    return ResultData.success("insert product succeed");
  }

  @Override
  @DeleteMapping("/delete")
  public ResultData<String> delete(@RequestParam("productCode") String productCode) {
    log.info("delete product,productCode is {}", productCode);
    productService.delete(productCode);
    return ResultData.success("delete product succeed");
  }

  @Override
  @PostMapping("/update")
  public ResultData<String> update(@RequestBody ProductDTO productDTO) {
    log.info("update product:{}", productDTO);
    productService.update(productDTO);
    return ResultData.success("update product succeed");
  }

  @Override
  @SentinelResource(value = "getByProductCode",fallback = "fallbackHandler")
  @GetMapping("/productCode/{productCode}")
  public ResultData<ProductDTO> getByProductCode(
      @PathVariable(value = "productCode") String productCode) {
    log.info("get productCode:{}", productCode);
    productService.getByProductCode(productCode);
    return ResultData.success("get product succeed");
  }

  @Override
  @GetMapping("/deduct")
  public ResultData<String> deduct(@RequestParam("productCode") String productCode,
      @RequestParam("count") Integer count) {
    log.info("deduct product, productCode:[{}],count:[{}]", productCode, count);
    productService.deduct(productCode, count);
    return ResultData.success("deduct product succeed");
  }

  /**
   * 自定义熔断异常
   * 返回值和参数要跟目标函数一样
   */
  public ResultData<ProductDTO> fallbackHandler(String productCode){
    return ResultData.error("服务被熔断了，不要调用!");
  }


}
